package listeners;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.regex.Pattern;

import javax.swing.JOptionPane;


import view.Block;
import view.DrawPanel;
import view.IfBlock;
import view.Line;
import view.OperationBlock;
import view.PictureModel;

public class SelectMouseListener extends MouseAdapter{
	private PictureModel pictureModel;
	private DrawPanel paint;
	public boolean isSelect = false;
	public Block select;
	public Point selectPoint;
	
	public SelectMouseListener(PictureModel pictureModel, DrawPanel paint){
		this.pictureModel = pictureModel;
		this.paint = paint;
	}
	@Override
	public void mouseClicked(MouseEvent event) {
		Point point = event.getPoint();
		Block block = pictureModel.getBlockByPoint(point);
		Line line = pictureModel.getLineByPoint(point);
		if(event.getClickCount() ==2 && (block instanceof OperationBlock || block instanceof IfBlock)){
			String value = JOptionPane.showInputDialog("Input new ID for block");
			if(value != null && !value.isEmpty() && isNumber(value)){
				block.setId(Integer.parseInt(value));
				block.cleanDraw(paint.getGraphics2D());
				block.draw(paint.getGraphics2D());
				paint.repaint();
			}
		}
		if(event.isAltDown() && block != null){
			if(!block.haveLine(pictureModel))
				pictureModel.removeBlock(block);
			else
				pictureModel.removeBlockWithLine(block);
			return;
		}else if(event.isAltDown() && line != null){
			if(line.contains(point)){
				pictureModel.removeLine(line);
			}
			return;
		}
	}

	@Override
	public void mousePressed(MouseEvent event) {
		Point point = event.getPoint();
		Block block = pictureModel.getBlockByPoint(point);
		if(block==null){
			return;
		}
		isSelect=true;
		select = block;
		selectPoint = point;
		paint.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
		
	}
	private boolean isNumber(String number) {
		Pattern pattern = Pattern.compile(".*[^0-9].*");
		return !pattern.matcher(number).matches();
	}

	@Override
	public void mouseReleased(MouseEvent event) {
		paint.setCursor(Cursor.getDefaultCursor());
		isSelect = false;
		select = null;
		selectPoint = null;
	}

}
